﻿using System.Collections;
using System.Collections.Generic;

namespace BaseSyntax.Values.StringTest.Yaml.Parsers
{
	public class RootParser
	{
		static List<string> GetAllGameObjs(Dictionary<string, object> d1)
		{
			List<string> gameObjectIds = new List<string>();
			
			foreach (object obj in d1.Values)
			{
				var dic = obj as Dictionary<string, object>;
				if (dic != null)
				{
					string UType = (string) dic["UType"];
					if (UType == "GameObject")
					{
						gameObjectIds.Add((string)dic["FileId"]);
					}
				}
			}

			return gameObjectIds;
		}

		static List<string> GetChildrenIds(Dictionary<string, object> d1)
		{
			List<string> childrenIds = new List<string>();

			// RectTransform节点
			List<string> transformIds = new List<string>();
			
			foreach (object obj in d1.Values)
			{
				var dic = obj as Dictionary<string, object>;
				if (dic != null)
				{
					if (dic.ContainsKey("m_Children"))
					{
						var arr = dic["m_Children"] as ArrayList;
						
						// 不为空数组
						if (arr != null && arr.Count > 0)
						{
							// 遍历子节点
							for (int i = 0; i < arr.Count; i++)
							{
								var obj1 = arr[i] as Dictionary<string, object>;
								if (obj1 != null)
								{
									string fileId = (string) obj1["fileID"];
									transformIds.Add(fileId);
								}
							}
						}
					}
				}
			}
			
			// 找到RectTransform对应的GameObject节点
			foreach (string transformId in transformIds)
			{
				var dic = d1[transformId] as Dictionary<string, object>;
				if (dic != null)
				{
					if (dic.ContainsKey("m_GameObject"))
					{
						var dic1 = dic["m_GameObject"] as Dictionary<string, object>;
						if (dic1 != null)
						{
							string id = (string) dic1["fileID"];
							childrenIds.Add(id);
						}
					}
				}
			}
			return childrenIds;
		}
		
		public static string GetRootId(Dictionary<string, object> d1)
		{
			List<string> gameObjectIds = GetAllGameObjs(d1);

			List<string> ChildrenIds = GetChildrenIds(d1);

			string id = "";

			foreach (string gameObjectId in gameObjectIds)
			{
				if (!ChildrenIds.Contains(gameObjectId))
				{
					id = gameObjectId;
					break;
				}
			}
			return id;
		}
	}
}